<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <script src="/js/spritejs.js"></script>
  <script src="//lib.baomitu.com/dat-gui/0.7.2/dat.gui.min.js"></script>
  <style>
    #adaptive {
      width: 100%;
      padding-bottom: 50%;
      background: #eee;
    }
  </style>
</head>
<body>
  <div id="timeline-ctrl">
    <button id="speed1">原速</button>
    <button id="speed2">2倍速</button>
    <button id="speed4">4倍速</button>
    <button id="halfSpeed">&#189;倍速</button>
    <button id="pause">静止</button>
    <button id="reversePlay">倒放</button>
  </div>
  <div id="adaptive"></div>
  <script>
    const {Scene, Sprite} = spritejs;
    const container = document.getElementById('adaptive');
    const scene = new Scene({
      container,
      width: 1200,
      height: 600,
      // contextType: '2d',
    });
    const layer = scene.layer();

    (async function () {
      await scene.preload({id: 'snow', src: 'https://p5.ssl.qhimg.com/t01bfde08606e87f1fe.png'});

      const [speed1, speed2, speed4, halfSpeed, pause, reversePlay]
        = document.querySelectorAll('#speed1, #speed2, #speed4, #halfSpeed, #pause, #reversePlay');

      const timeline = layer.timeline;

      speed1.addEventListener('click', (evt) => {
        timeline.playbackRate = 1.0;
      });

      speed2.addEventListener('click', (evt) => {
        timeline.playbackRate = 2.0;
      });

      speed4.addEventListener('click', (evt) => {
        timeline.playbackRate = 4.0;
      });

      halfSpeed.addEventListener('click', (evt) => {
        timeline.playbackRate = 0.5;
      });

      pause.addEventListener('click', (evt) => {
        timeline.playbackRate = 0;
      });

      reversePlay.addEventListener('click', (evt) => {
        timeline.playbackRate = -1.0;
      });


      function addRandomSnow() {
        const snow = new Sprite('snow');
        const x0 = 20 + Math.random() * 1100,
          y0 = -100;

        snow.attr({
          anchor: [0.5, 0.5],
          pos: [x0, y0],
          size: [50, 50],
        });

        snow.animate([
          {x: x0 - 10},
          {x: x0 + 10},
        ], {
          duration: 1000,
          fill: 'forwards',
          direction: 'alternate',
          iterations: Infinity,
          easing: 'ease-in-out',
        });

        const dropAnim = snow.animate([
          {y: -100, rotate: 0},
          {y: 700, rotate: 360},
        ], {
          duration: 10000,
          fill: 'forwards',
        });

        dropAnim.finished.then(() => {
          snow.remove();
        });

        layer.append(snow);
      }

      setInterval(addRandomSnow, 200);
    }());
  </script>
</body>
</html>
